import json
from os import listdir, system, makedirs
from utils.restApi import postFrame
from utils.config import logpath, picApi_url, result_path, backup_path, camerasIdx
from os.path import join, isdir, basename, getmtime
from tendo.singleton import SingleInstance
from utils.logger import Logger
import time
import cv2

trans_logger = Logger(filename=f'{logpath}/result_transfer.log').logger
trans_logger.info("result_transfer start!")

try:
    Single = SingleInstance()
except:
    trans_logger.error('road transfer process already  exist! ')
    exit()

def putText(im, lon, lat, time, pos=(100,100)):
    overlay = im.copy()
    x = pos[0]
    y = pos[1]
    cv2.putText(overlay, lon, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 150, 150, 0.8), 3)
    cv2.putText(overlay, lat, (x, y + 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 150, 150, 0.8), 3)
    cv2.putText(overlay, time, (x, y + 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (150, 150, 150, 0.8), 3)
    cv2.addWeighted(overlay, 0.5, im, 0.5, 0, im)
    return im

def resultTransferSever():
    dataPath = join(result_path, 'data')
    while True:
        time.sleep(0.5)
        dataFiles = listdir(dataPath)
        dataFiles.sort()
        for file in dataFiles:
            if file.split('.')[-1] != 'json':
                continue
            datafile = join(dataPath, file)
            if time.time() - getmtime(datafile) < 1:
                continue
            with open(datafile) as f:
                content = f.read()
                if not content:
                    continue
                data = json.loads(content)

            r = postFrame(picApi_url, data)
            if r is None:
                trans_logger.error('postFrame return None')
                time.sleep(1)
                continue
            elif r == 'Connection refused':
                time.sleep(1)
                continue
            else:
                trans_logger.info(f"{r}, {r.text}")
            result = json.loads(r.text)


            imgSaveDir = data["imgSaveDir"]
            img_bakdir = join(backup_path, 'images')
            if not isdir(img_bakdir):
                makedirs(img_bakdir)

            i = 0
            auto = ''
            for file in listdir(imgSaveDir):
                i += 1
                auto = file.split("_")[-1].split('.')[0]

                if result['msg'] == 'success':
                    system(f"mv {join(imgSaveDir, file)}  {img_bakdir}/{basename(imgSaveDir)}_{file}")
                else:
                    trans_logger.error(result['msg'])

            if auto == '00':
                if i == len(camerasIdx):
                    trans_logger.info("\n" + "=" * 30 + f"\n 手动拍摄图片" + "   上传成功!  " + "\n" + "=" * 30)
                else:
                    trans_logger.info("\n" + "*" * 30 + f"\n 手动拍摄图片 部分缺失!  " + "\n" + "*" * 30)
            elif auto == '01':
                trans_logger.info("\n" + "=" * 30 + f"\n 自动拍摄图片" + "   上传成功!  " + "\n" + "=" * 30)

            if not len(listdir(imgSaveDir)):
                data_bakdir = join(backup_path, 'data')
                if not isdir(data_bakdir):
                    makedirs(data_bakdir)
                system(f'rm -rf {imgSaveDir}')
                system(f"mv {datafile} {data_bakdir}")
        # time.sleep(0.1)


if __name__ == '__main__':
    resultTransferSever()
